package com.taotao.st3.sharding5.ext.sharding;

import com.google.common.collect.Range;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;


/**
 * 以月份进行分表策略
 *
 */
@Slf4j
public class DateStandardShardingAlgorithm implements StandardShardingAlgorithm<Date> {
    private static final DateFormat YYYY_MM = new SimpleDateFormat("yyyyMM");


    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {

        log.info("-------------collection={},rangeShardingValue={}", collection, rangeShardingValue);

        Collection<String> result = new HashSet<>();
        Range<Date> ranges = rangeShardingValue.getValueRange();
        Date startTime = ranges.lowerEndpoint();
        Date endTime = ranges.upperEndpoint();
        // 此处应该返回 tablePrefix+201808 , tablePrefix+201809,tablePrefix+201810,
        Calendar cal = Calendar.getInstance();


        final String logicTableName = rangeShardingValue.getLogicTableName();

        while (startTime.getTime() <= endTime.getTime()) {
            result.add(logicTableName + YYYY_MM.format(startTime));
            // 设置起时间
            cal.setTime(startTime);
            cal.add(Calendar.MONTH, 1);
            startTime = cal.getTime();
        }
        return result;
    }


    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        log.info("-------------collection={},preciseShardingValue={}", collection, preciseShardingValue);

        return preciseShardingValue.getLogicTableName() + YYYY_MM.format(preciseShardingValue.getValue());
    }
}
